<template>
  <div>
    <div class="gva-search-box">
      <el-form ref="searchForm" :inline="true" :model="searchInfo">
        <el-form-item label="">
          <el-input v-model="searchInfo.serviceName" placeholder="请输入业务应用名称" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="onSubmit">查询</el-button>
          <el-button icon="refresh" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button type="primary" icon="plus" @click="addService">新增</el-button>
      </div>
      <el-table :data="sortedData" row-key="ServiceId" @sort-change="sortChange">
        <el-table-column align="left" label="序号" min-width="80" v-slot="scope">
          {{ (page - 1) * pageSize + scope.$index + 1 }}
        </el-table-column>
        <el-table-column align="left" label="业务应用名称" min-width="150" prop="Name" sortable />
        <el-table-column align="left" label="联系人" min-width="150" prop="UserName" sortable />
        <el-table-column align="left" label="电话" min-width="150" prop="Phone" sortable />
        <el-table-column align="left" label="应用类型" min-width="150" prop="AppType" sortable />

        <el-table-column align="left" label="许可服务能力" min-width="150">
          <template #default="scope">
            <el-button
                type="primary"
                link
                @click="goToliccap(scope.row.AppId)"
            >
              查看
            </el-button>
          </template>
        </el-table-column>
        <el-table-column align="left" label="许可数据" min-width="150">
          <template #default="scope">
            <el-button
                type="primary"
                link
                @click="goTolicdata(scope.row.AppId)"
            >
              查看
            </el-button>
          </template>
        </el-table-column>
        <el-table-column align="left" label="状态" min-width="100" prop="Status" sortable />
        <el-table-column align="left" label="创建时间" min-width="180" prop="CreatedAt" sortable>
          <template #default="scope">
            {{ formatDate(scope.row.CreatedAt) }}
          </template>
        </el-table-column>




        <el-table-column align="left" fixed="right" label="操作" width="300">
          <template #default="scope">

            <el-button icon="edit" type="primary" link @click="openDetailDialog(scope.row)">编辑</el-button>
            <el-button icon="delete" type="primary" link @click="deleteService(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
            :current-page="page"
            :page-size="pageSize"
            :page-sizes="[10, 30, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
        />
      </div>
    </div>
    <el-drawer v-model="detailDialog" size="60%" :show-close="false" :close-on-press-escape="false" :close-on-click-modal="false">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg">业务应用详情</span>
          <div>
            <el-button @click="closeDetailDialog">取消</el-button>
            <el-button type="primary" v-show="flagS" @click="submitDetailForm">确定</el-button>
            <el-button type="primary" v-show="flagU" @click="updateDetailForm">保存</el-button>
          </div>
        </div>
      </template>
      <el-form ref="detailForm" :rules="rules" :model="serviceInfo" label-width="120px">
        <div style="margin: 20px">
          <p><strong>业务应用授权信息</strong></p>
        </div>
        <el-form-item label="业务应用id" prop="AppId">
          <el-input v-model="serviceInfo.AppId" disabled />
        </el-form-item>
        <el-form-item label="授权码" prop="AuthCode">
          <el-input v-model="serviceInfo.AuthCode" />
        </el-form-item>
        <div style="margin: 20px">
          <p><strong>业务应用详情</strong></p>
        </div>
        <el-form-item label="业务应用名称" prop="Name">
          <el-input v-model="serviceInfo.Name" />
        </el-form-item>
        <el-form-item label="联系人" prop="userName">
          <el-input v-model="serviceInfo.UserName" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="serviceInfo.Phone" />
        </el-form-item>
        <el-form-item label="应用类型" prop="appType">
          <el-select v-model="serviceInfo.AppType" placeholder="请选择应用类型">
            <el-option label="数据资产" value="数据资产"></el-option>
            <el-option label="溯源验真" value="溯源验真"></el-option>
            <el-option label="跨境电商" value="跨境电商"></el-option>
            <el-option label="社交文旅" value="社交文旅"></el-option>
          </el-select>
        </el-form-item>

      </el-form>
    </el-drawer>


  </div>
</template>

<script setup>
import { ref, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getlistApp,addApp,updateApp,deleteApp } from '@/api/application'
import { useRouter } from "vue-router";

const page  = ref(1)
const total = ref(0)
const pageSize = ref(10)
const sortInfo = ref({ prop: '', order: '' })
const searchInfo = ref({ Name: '' })
const router = useRouter();

const flagS=ref(false)
const flagU=ref(false)
const originalTableData = ref([])
const licenseDialog = ref(false)
const licenseInfo = ref({})

const openLicenseDialog = (row) => {
  // 模拟获取业务许可配置信息的 API 调用
  licenseInfo.value = { ...row }
  licenseDialog.value = true
}

const closeLicenseDialog = () => {
  licenseDialog.value = false
}

const tableData = ref([])

const filteredData = computed(() => {
  const filterValue = searchInfo.value.Name.toLowerCase()
  return (tableData.value || []).filter(item =>
      item.Name.toLowerCase().includes(filterValue)
  )
})

const formatDate = (dateString) => {
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

const sortedData = computed(() => {
  const data = [...filteredData.value]
  if (sortInfo.value.prop && sortInfo.value.order) {
    data.sort((a, b) => {
      let aValue = a[sortInfo.value.prop]
      let bValue = b[sortInfo.value.prop]
      if (sortInfo.value.prop === 'UpdatedAt') {
        aValue = new Date(aValue).getTime()
        bValue = new Date(bValue).getTime()
      } else if (sortInfo.value.prop === 'ServiceVersion') {
        aValue = parseInt(aValue)
        bValue = parseInt(bValue)
      }
      if (sortInfo.value.order === 'ascending') {
        return aValue > bValue ? 1 : -1
      } else {
        return aValue < bValue ? 1 : -1
      }
    })
  }
  return data
})

const handleCurrentChange = async (newPage) => {
  page.value = newPage;
  await getTableData(); // 根据新的页码请求数据
};

const handleSizeChange = async (newSize) => {
  pageSize.value = newSize;
  await getTableData(); // 根据新的每页条数请求数据
};

const getTableData = async () => {
  try {
    const response = await getlistApp(pageSize.value, page.value); // 使用最新的页码和每页条数
    if (response.code === 0) {
      tableData.value = response.data.list; // 更新表格数据
      total.value = response.data.total;     // 更新总条数
    } else {
      console.error('API Error: ', response.message);
      ElMessage.error('获取数据失败');
    }
  } catch (error) {
    console.error('API Error:', error);
    ElMessage.error('获取数据失败');
  }
};

// 初始化数据
getTableData();





const onSubmit = () => {
  // 过滤原始数据
  const filterValue = searchInfo.value.serviceName.toLowerCase();
  const filtered = originalTableData.value.filter(item =>
    item.Name.toLowerCase().includes(filterValue)
  );
  // 更新表格数据为过滤后的数据
  tableData.value = filtered;
}


const onReset = () => {
  // 清空搜索框内容
  searchInfo.value.serviceName = '';
  // 重置表格数据为原始数据
  tableData.value = [...originalTableData.value];
}

const detailDialog = ref(false)
const serviceInfo = ref({
  Name:'',
  UserName:'',
  Phone:'',
  AppType:'',
  Status:'上线',
  AuthCode:'',
})

const rules = ref({
  businessName: [{ required: true, message: '请输入业务应用名称', trigger: 'blur' }],
  authorization: [{ required: true, message: '请输入授权信息', trigger: 'blur' }],
  application: [{ required: true, message: '请输入许可配置', trigger: 'blur' }],
});


const addService = () => {
  detailDialog.value = true
  flagS.value=true
  serviceInfo.value = {
    Name:'',
  UserName:'',
  Phone:'',
  AppType:'',
    Status:'',
  }
}

const openDetailDialog = (row) => {
  serviceInfo.value = {...row}
  console.log("serviceInfo:",serviceInfo.value)
  detailDialog.value = true
  flagU.value=true
}

const closeDetailDialog = () => {
  detailDialog.value = false
  flagS.value=false
  flagU.value=false
}

const submitDetailForm = async () => {
  try {
    // 调用 API 添加服务
    console.log("添加的数据：",serviceInfo.value);
    await addApp(serviceInfo.value);

    ElMessage.success('服务新增成功');
    closeDetailDialog();
    await getTableData(); // 刷新表格数据
  } catch (error) {
    console.error('新增服务失败', error);
    ElMessage.error('新增服务失败');
  }
};

const updateDetailForm = async () => {
  try {
    // 调用 API 添加服务
    console.log(serviceInfo.value)
    await updateApp(serviceInfo.value)

    ElMessage.success('服务修改成功')
    closeDetailDialog()
    await getTableData() // 刷新表格数据
  } catch (error) {
    console.error('修改失败', error)
    ElMessage.error('修改服务失败')
  }
}

const deleteService = async (row) => {
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      // 调用 API 删除服务
      let param = ''; // 使用 let 声明
      console.log('appid is there:', row.AppId);
      param = row.AppId; // 使用模板字符串

      await deleteApp({"appId":param}); // 调用删除 API

      ElMessage.success('服务删除成功');
      await getTableData(); // 刷新表格数据
    } catch (error) {
      console.error('删除服务失败', error);
      ElMessage.error('删除服务失败');
    }
  }).catch(() => {
    ElMessage.info('取消删除');
  });
};


const sortChange = ({prop, order}) => {
  sortInfo.value = {prop, order}
}
const goToliccap = (AppId) => {
  router.push({ path: "./licensedcap", query: { AppId } });
};

const goTolicdata = (AppId) => {
  router.push({ path: "./licenseddata", query: { AppId } });
};


</script>

<style scoped>
.gva-search-box {
  margin-bottom: 20px;
}

.gva-btn-list {
  margin-bottom: 20px;
}

.gva-table-box {
  margin-top: 20px;
}

.gva-pagination {
  margin-top: 20px;
}
</style>